package com.witframework.components;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.witframework.core.ApplicationProperties;
import com.witframework.core.persistence.IBaseJdbcDao;
import com.witframework.web.mvc.Controller;
import com.witframework.web.mvc.WebContext;
import com.witframework.web.tree.TreeItem;
import com.witframework.web.tree.TreeNode;
import com.witframework.web.tree.TreeUserdata;

@Component
public class CustomSelectTreeController implements Controller{


	public String treepage(WebContext webContext) {		
		return "classpath:/com/witframework/webroot/framework/common/components/selecttree.jsp.wit?"+webContext.getHttpRequest().getQueryString();
	}
	/**
	public String executor(WebContext webContext) {
		String dialogid=webContext.getParameterAndsetAttribute("treeid");
		String data=webContext.getParameterAndsetAttribute("data");
		String data2=webContext.getParameterAndsetAttribute("data2");
		//指向父节点的属性名称
		String parentid=webContext.getParameterAndsetAttribute("parentid");		
		//树节点的标识属性名称
		String idname=webContext.getParameterAndsetAttribute("nodeid");
		String idname2=webContext.getParameterAndsetAttribute("nodeid2");
		//树节点的显示属性名称
		String labelname=webContext.getParameterAndsetAttribute("nodelabel");
		String labelname2=webContext.getParameterAndsetAttribute("nodelabel2");
		//树节点的附加属性名称列表
		String others=webContext.getParameterAndsetAttribute("others");		
		//数据源类型
		String datatype=webContext.getParameterAndsetAttribute("datatype");
		//是否允许多选
		String multiple=webContext.getParameterAndsetAttribute("multiple");
		//默认的选中项
		String selected=webContext.getParameterAndsetAttribute("selected");		
		//数据的预置过滤条件
		String filters=webContext.getParameterAndsetAttribute("filters");
		String onlyLeaf=webContext.getParameterAndsetAttribute("onlyLeaf");
		
		String id=webContext.getParameterAndsetAttribute("id");		
		String rootid=webContext.getParameterAndsetAttribute("root");		
		
		try {
			data=java.net.URLDecoder.decode(data,"utf-8");
			data2=java.net.URLDecoder.decode(data2,"utf-8");
			filters=java.net.URLDecoder.decode(filters,"utf-8");
		}catch (Exception e) {			
		}
		
		
		if(id==null) id=rootid;
		
		TreeNode treeNode = new TreeNode();
		TreeItem root = new TreeItem(id, "root");
		root.setTooltip("ROOT");
		treeNode.setRootNode(root);		
		
		List dataList=null;
		if(datatype.equalsIgnoreCase("table")||datatype.equalsIgnoreCase("sql")){
			IBaseJdbcDao dao=(IBaseJdbcDao)com.witframework.core.BeanFactory.getBean("baseJdbcDao");			
			StringBuffer query=new StringBuffer();
			if(datatype.equalsIgnoreCase("table")){
				if(StringUtils.isNotEmpty(others)){
					query.append("select "+idname+" "+idname+","+labelname+" "+labelname+","+others+" from "+data+" where "+parentid+"='"+id+"'");
					for(String property:others.split(",")){
						query.insert(query.indexOf(property)+property.length()," "+property);
					}
				}else{
					query.append("select "+idname+" "+idname+","+labelname+" "+labelname+" from "+data);
					if(StringUtils.isNotEmpty(parentid))
						query.append(" where "+parentid+"='"+id+"'");
				}
				if(StringUtils.isNotEmpty(filters)){
					if(query.toString().toLowerCase().indexOf(" where ")<0){
						if(query.toString().toLowerCase().indexOf(" order ")<0)
							query.append(" where ").append(filters);
						else
							query.insert(query.toString().toLowerCase().indexOf(" order "), " where "+filters);
					}else{
						query.insert(query.toString().toLowerCase().indexOf(" where ")+7, filters+" and ");
					}
				}
			}else{
				if(StringUtils.isNotEmpty(data2)){//对于SQL类型的，支持从两个数据源选在数据(即两个结果集)
					if(id.equals(rootid)){//所有的第一层根节点数据从data2选取
						query.append(data2);
					}else{						
						query.append(data);
						if(StringUtils.isNotEmpty(parentid)){
							if(query.indexOf(" where ")>0)
								query.insert(query.indexOf(" where ")+7, parentid+"='"+id+"' and ");
							else
								query.append(" where "+parentid+"='"+id+"'");
						}
					}
				}else if(StringUtils.isNotEmpty(data)){
					query.append(data);
					if(StringUtils.isNotEmpty(parentid)){
						if(query.indexOf(" where ")>0)
							query.insert(query.indexOf(" where ")+7, parentid+"='"+id+"' and ");
						else
							query.append(" where "+parentid+"='"+id+"'");
					}
				}
			}	
			if(query.length()>0)
				dataList=dao.queryForList(query.toString());			
			
			for(Object p:dataList){
				Map pMap=(Map)p;
				String nodeid;
				String nodetext;
				if(id.equals(rootid)&&StringUtils.isNotEmpty(data2)){
					nodeid=(String)pMap.get(idname2);
					nodetext=(String)pMap.get(labelname2);
				}else{
					nodeid=(String)pMap.get(idname);
					nodetext=(String)pMap.get(labelname);
				}
				String parentnodeid=(String)pMap.get(parentid);
				if(nodeid!=null){
					TreeItem childNode = new TreeItem(nodeid,nodetext);
					if(rootid.equals(id)) childNode.setOpen(true);
					if(StringUtils.isNotEmpty(others)){
						String udValue="";
						for(String property:others.split(",")){
							udValue=pMap.get(property)+",";
						}
						TreeUserdata ud=new TreeUserdata("others",udValue.substring(0,udValue.length()-1));
						childNode.addUserdata(ud);
					}
					if(StringUtils.isNotEmpty(data)){
						StringBuffer childrenSql=new StringBuffer(data);
						if(StringUtils.isNotEmpty(data2)&&id.equals(rootid)){
							if(data.indexOf(" where ")>0)
								childrenSql.insert(data.indexOf(" where ")+7,parentid+"='"+nodeid+"' and ");
							else
								childrenSql.append(" where "+parentid+"='"+nodeid+"'");
						}
						else
							childrenSql=new StringBuffer(StringUtils.replace(query.toString(), parentid+"='"+id+"'", parentid+"='"+nodeid+"'"));
						List children=dao.queryForList(childrenSql.toString());					
						childNode.setChild(children.size());
					}else{
						childNode.setChild(0);
					}					
					
					if(onlyLeaf==null||onlyLeaf.equalsIgnoreCase("true")||onlyLeaf.equalsIgnoreCase("1")){
						if(childNode.getChild()==0)
							childNode.setCheckbox(true);
						else
							childNode.setCheckbox(false);
					}else{
						childNode.setCheckbox(true);
					}
					treeNode.addItem(childNode);
				}				
			}			
			
		}else{
			webContext.renderHtml("不支持的数据源类型："+datatype);
		}		
		String xml=treeNode.outString();
		webContext.renderXml(xml);
		return null;
	}		
	*/
	public String executor(WebContext webContext) {		
		String data=webContext.getParameterAndsetAttribute("data");
		String data2=webContext.getParameterAndsetAttribute("data2");
		//指向父节点的属性名称
		String parentid=webContext.getParameterAndsetAttribute("parentid");		
		String parentid2=webContext.getParameterAndsetAttribute("parentid2");		
		//树节点的标识属性名称
		String idname=webContext.getParameterAndsetAttribute("nodeid");
		String idname2=webContext.getParameterAndsetAttribute("nodeid2");
		//树节点的显示属性名称
		String labelname=webContext.getParameterAndsetAttribute("nodelabel");
		String labelname2=webContext.getParameterAndsetAttribute("nodelabel2");
		//树节点的附加属性名称列表
		String others=webContext.getParameterAndsetAttribute("others");		
		//数据源类型
		String datatype=webContext.getParameterAndsetAttribute("datatype");
		//是否允许多选
		String multiple=webContext.getParameterAndsetAttribute("multiple");
		//默认的选中项
		String selected=webContext.getParameterAndsetAttribute("selected");

		String onlyLeaf=webContext.getParameterAndsetAttribute("onlyLeaf");
		
		String id=webContext.getParameterAndsetAttribute("id");		
		String rootid=webContext.getParameterAndsetAttribute("root");
		
		try {
			data=java.net.URLDecoder.decode(data,"utf-8");
			data2=java.net.URLDecoder.decode(data2,"utf-8");			
		}catch (Exception e) {			
		}
		
		
		if(id==null) id=rootid;
		
		TreeNode treeNode = new TreeNode();
		TreeItem root = new TreeItem(id, "root");
		root.setTooltip("ROOT");
		treeNode.setRootNode(root);		
		
		List dataList=null;
		if(datatype.equalsIgnoreCase("table")||datatype.equalsIgnoreCase("sql")){
			IBaseJdbcDao dao=(IBaseJdbcDao)com.witframework.core.BeanFactory.getBean("baseJdbcDao");			
			StringBuffer query=new StringBuffer();
			if(datatype.equalsIgnoreCase("table")){
				if(StringUtils.isNotEmpty(others)){
					query.append("select "+idname+" "+idname+","+labelname+" "+labelname+","+others+" from "+data+" where "+parentid+"='"+id+"'");
					for(String property:others.split(",")){
						query.insert(query.indexOf(property)+property.length()," "+property);
					}
				}else{
					query.append("select "+idname+" "+idname+","+labelname+" "+labelname+" from "+data);
					if(StringUtils.isNotEmpty(parentid))
						query.append(" where "+parentid+"='"+id+"'");
				}
				dataList=dao.queryForList(query.toString());
			}else{
				if(StringUtils.isNotEmpty(data2)){//对于SQL类型的，支持从两个数据源选在数据(即两个结果集)
					if(id.equals(rootid)||id.startsWith("root_")){//所有的第一层根节点数据从data2选取
						query.append(data2);						
						if(query.indexOf(" where ")>0)
							query.insert(query.indexOf(" where ")+7, parentid2+"='"+(id.startsWith("root_")?id.substring(5):id)+"' and ");
						else
							query.append(" where "+parentid2+"='"+(id.startsWith("root_")?id.substring(5):id)+"'");
						
						dataList=dao.queryForList(query.toString());
						reset(dataList,"1");
						if(id.startsWith("root_")){
							query=new StringBuffer(data);
							if(StringUtils.isNotEmpty(parentid)){
								if(query.indexOf(" where ")>0)
									query.insert(query.indexOf(" where ")+7, parentid+"='"+id.substring(5)+"' and ");
								else
									query.append(" where "+parentid+"='"+id.substring(5)+"'");
							}							
							dataList.addAll(dao.queryForList(query.toString()));	
						}
					}					
					else{						
						query.append(data);
						if(StringUtils.isNotEmpty(parentid)){							
							if(query.indexOf(" where ")>0)
								query.insert(query.indexOf(" where ")+7, parentid+"='"+(id.startsWith("root_")?id.substring(5):id)+"' and ");
							else
								query.append(" where "+parentid+"='"+(id.startsWith("root_")?id.substring(5):id)+"'");
						}
						dataList=dao.queryForList(query.toString());
					}
				}else if(StringUtils.isNotEmpty(data)){
					query.append(data);
					if(StringUtils.isNotEmpty(parentid)){
						if(query.indexOf(" where ")>0)
							query.insert(query.indexOf(" where ")+7, parentid+"='"+id+"' and ");
						else
							query.append(" where "+parentid+"='"+id+"'");
					}
					dataList=dao.queryForList(query.toString());
				}
			}						
			
			for(Object p:dataList){
				Map pMap=(Map)p;
				String nodeid;
				String nodetext;
				if(pMap.get("root_")!=null){
					nodeid="root_"+(String)pMap.get(idname2);
					nodetext=(String)pMap.get(labelname2);
				}else{
					nodeid=(String)pMap.get(idname);
					nodetext=(String)pMap.get(labelname);
				}				
				if(nodeid!=null){
					TreeItem childNode = new TreeItem(nodeid,nodetext);
					String img0=null;
					if(pMap.get("root_")!=null){
						img0=ApplicationProperties.getProperty("icon_"+labelname2);
					}else{
						img0=ApplicationProperties.getProperty("icon_"+labelname);
					}
					if(img0!=null){
						childNode.setImg0(img0);
						childNode.setImg1(img0);
						childNode.setImg2(img0);
					}
					if(rootid.equals(id)) childNode.setOpen(true);
					if(StringUtils.isNotEmpty(others)){
						String udValue="";
						for(String property:others.split(",")){
							udValue=pMap.get(property)+",";
						}
						TreeUserdata ud=new TreeUserdata("others",udValue.substring(0,udValue.length()-1));
						childNode.addUserdata(ud);
					}
					if(StringUtils.isNotEmpty(data)){
						int childsize=0;
						StringBuffer childrenSql;
						if(StringUtils.isNotEmpty(data2)&&(id.equals(rootid)||id.startsWith("root_"))){
							childrenSql=new StringBuffer(data2);
							if(data2.indexOf(" where ")>0)
								childrenSql.insert(data2.indexOf(" where ")+7,parentid2+"='"+nodeid.substring(5)+"' and ");
							else
								childrenSql.append(" where "+parentid2+"='"+nodeid.substring(5)+"'");
							childsize=dao.queryForList(childrenSql.toString()).size();		
							childrenSql=new StringBuffer(data);
							if(StringUtils.isNotEmpty(parentid)){							
								if(childrenSql.indexOf(" where ")>0)
									childrenSql.insert(childrenSql.indexOf(" where ")+7, parentid+"='"+(nodeid.startsWith("root_")?nodeid.substring(5):nodeid)+"' and ");
								else
									childrenSql.append(" where "+parentid+"='"+(nodeid.startsWith("root_")?nodeid.substring(5):nodeid)+"'");
							}
							childsize+=dao.queryForList(childrenSql.toString()).size();
							childNode.setChild(childsize);
						}
						else{
							childrenSql=new StringBuffer(StringUtils.replace(query.toString(), parentid+"='"+id+"'", parentid+"='"+(nodeid.startsWith("root_")?nodeid.substring(5):nodeid)+"'"));						
							childNode.setChild(dao.queryForList(childrenSql.toString()).size());
						}
					}				
					
					if(onlyLeaf==null||onlyLeaf.equalsIgnoreCase("true")||onlyLeaf.equalsIgnoreCase("1")){
						if(childNode.getChild()==0&&!childNode.getId().startsWith("root_"))
							childNode.setCheckbox(true);
						else
							childNode.setCheckbox(false);
					}else{
						childNode.setCheckbox(true);
					}
					treeNode.addItem(childNode);
				}				
			}			
			
		}else{
			webContext.renderHtml("不支持的数据源类型："+datatype);
		}		
		String xml=treeNode.outString();
		webContext.renderXml(xml);
		return null;
	}		
	private List<Map> reset(List<Map> ds,String flag){
		for(int i=0;i<ds.size();i++){
			Map d=(Map)ds.get(i);
			d.put("root_",flag);
			ds.remove(i);
			ds.add(i, d);
		}
		return ds;
	}
}
